package com.example.administrator.newxlmedical;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.administrator.baseproject.BaseActivity;

import java.util.ArrayList;
import java.util.List;

import adapters.ComboModifyAndAddAdapter;
import beans.ComboInfoBean;
import beans.PutComboBean;
import beans.PutComboResultBean;
import beans.WarningInfoBean;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import constants.Constants;
import constants.HandlerConstant;
import customhandler.MyHandler;
import netframe.GetRetrofit;
import netframe.NetAddress;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import singleton.SingletonClass;
import utils.ActivityUtil;
import utils.CardinalNumberSortUtils;
import utils.DigitalTrans;
import utils.TimeUtil;
import utils.ToastUtil;
import utils.ViewUtil;

public class ComboModifyAndAddActivity extends BaseActivity implements ComboModifyAndAddAdapter.ComboMofifyAndAddListener {

    @BindView(R.id.tv_combo_modify_and_add_title_content)
    TextView tvTitleContent;
    @BindView(R.id.iv_combo_modify_and_add_home)
    ImageView ivHome;
    @BindView(R.id.et_combo_modify_and_add_combo_name)
    EditText etComboName;
    @BindView(R.id.tv_combo_modify_and_add_goods)
    TextView tvGoods;
    @BindView(R.id.iv_warn_set_goods_sort)
    ImageView ivGoodsSort;
    @BindView(R.id.rl_combo_modify_and_add_goods_sort)
    RelativeLayout rlGoodsSort;
    @BindView(R.id.tv_combo_modify_and_add_size)
    TextView tvSize;
    @BindView(R.id.iv_warn_set_specification_sort)
    ImageView ivSpecificationSort;
    @BindView(R.id.rl_combo_modify_and_add_specification_sort)
    RelativeLayout rlSpecificationSort;
    @BindView(R.id.tv_combo_modify_and_add_supplier)
    TextView tvSupplier;
    @BindView(R.id.iv_warn_set_supplier_sort)
    ImageView ivSupplierSort;
    @BindView(R.id.rl_combo_modify_and_add_supplier_sort)
    RelativeLayout rlSupplierSort;
    @BindView(R.id.rv_combo_modify_and_add_activity)
    RecyclerView recyclerview;
    @BindView(R.id.fl_combo_modify_and_add_empty)
    FrameLayout flEmpty;
    @BindView(R.id.tv_combo_modify_and_add_number)
    TextView tvNumber;
    @BindView(R.id.tv_combo_modify_and_addstar_data)
    TextView tvStarData;
    @BindView(R.id.tv_combo_modify_and_add_button)
    TextView tvModifyAndAddButton;
    @BindView(R.id.iv_combo_modify_and_add_return)
    ImageView ivReturn;
    @BindView(R.id.ll_combo_modify_and_add)
    LinearLayout llComboModifyAndAdd;
    private ArrayList<WarningInfoBean.DataBean> list = new ArrayList<>();
    private ArrayList<WarningInfoBean.DataBean> sortList = new ArrayList<>();
    private ArrayList<ComboInfoBean.DataBean> comboInfolist = new ArrayList<>();
    private ArrayList<String> idList = new ArrayList<>();
    private boolean flag;
    private ArrayList<WarningInfoBean.DataBean> modifyList = new ArrayList<>(); //传给接口的实体类集合
    private ComboModifyAndAddAdapter adapter;
    private int resultType;
    private ArrayList<String> comboNameList;
    private int comboID;
    private MyHandler allHandler = SingletonClass.getSingleton(MyHandler.class);
    private SharedPreferences sharedPreferences;
    private int anInt;
    private boolean isSortGoods, isSortSpecification, isSortSupplier;
    private int sortGoods, sortSpecification, sortSupplier;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_combo_modify_and_add);
        ButterKnife.bind(this);
        sharedPreferences = ActivityUtil.getSharedPreferences(this);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        recyclerview.setLayoutManager(manager);
        adapter = new ComboModifyAndAddAdapter(this, list, this);
        recyclerview.setAdapter(adapter);

        Intent intent = getIntent();
        String type = intent.getStringExtra("type");
        String comboName = intent.getStringExtra("comboName");
        comboNameList = intent.getStringArrayListExtra("comboNameList");
        comboID = intent.getIntExtra("id", 0);

        // 从集合中移除当前套餐名， 修改时要用
        comboNameList.remove(comboName);

        anInt = sharedPreferences.getInt(Constants.COMBO_BATCH_NUMBER, 1);
        if (type.equals("添加")) {
            resultType = 1;
            tvTitleContent.setText("添加新套餐");
            tvModifyAndAddButton.setText("提交");
            etComboName.setText("未命名" + TimeUtil.getShowDate() + " - Z" + DigitalTrans.integerToint(anInt,3));
        } else {
            resultType = 2;
            etComboName.setText(comboName);
            tvTitleContent.setText("套餐修改");
            tvModifyAndAddButton.setText("保存");
        }

        tvStarData.setText(TimeUtil.getShowDate());

        if (comboID != 0) {
            getComboInfoData(comboID);
        } else {
            getData();
        }

    }

    @OnClick({R.id.iv_combo_modify_and_add_home, R.id.tv_combo_modify_and_add_button, R.id.iv_combo_modify_and_add_return,
            R.id.rl_combo_modify_and_add_goods_sort,R.id.rl_combo_modify_and_add_specification_sort,R.id.rl_combo_modify_and_add_supplier_sort})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_combo_modify_and_add_home:
                ActivityUtil.jumpToActivity(this, MainActivity.class);
                finish();
                break;
            case R.id.tv_combo_modify_and_add_button:
                String comboName = etComboName.getText().toString();
                commit(comboName);
                break;
            case R.id.iv_combo_modify_and_add_return:
                finish();
                break;
            case R.id.rl_combo_modify_and_add_goods_sort:
                sort(1);
                break;
            case R.id.rl_combo_modify_and_add_supplier_sort:
                sort(2);
                break;
            case R.id.rl_combo_modify_and_add_specification_sort:
                sort(3);
                break;
        }
    }

    private void commit(String comboName) {
        if (!TextUtils.isEmpty(comboName)) {
            if (!comboNameList.contains(comboName)) {
                if (idList.size() != 0) {
                    PutComboBean putComboBean = new PutComboBean();
                    PutComboBean.GoodsPackageBean bean = new PutComboBean.GoodsPackageBean();
                    bean.setGoodsInfoId(idList);
                    bean.setPackageName(etComboName.getText().toString());
                    bean.setSubTime(tvStarData.getText().toString());
                    bean.setGoodsPackageId(comboID);
                    putComboBean.setGoodsPackage(bean);
                    putCombo(putComboBean);
                } else {
                    ToastUtil.showToast(this, "请至少勾选一个物品 !");
                }

            } else {
                ToastUtil.showToast(this, "套餐名已存在 !");
            }

        } else {
            ToastUtil.showToast(this, "请输入套餐名 !");
        }
    }

    /**
     *  提交 添加、更改的套餐
     * @param bean
     */
    private void putCombo(PutComboBean bean) {
        hideEmptyView();
        showLoadingView(flEmpty, "正在提交，请稍后 . . .");
        GetRetrofit.getInstance().putCombo(NetAddress.token, NetAddress.machineCode, bean)
                .enqueue(new Callback<PutComboResultBean>() {
                    @Override
                    public void onResponse(Call<PutComboResultBean> call, Response<PutComboResultBean> response) {
                        hideLoadingView();
                        if (response.code() == 200 && !response.body().getResult().equals("no")) {

                            if (resultType == 1) {
                                SharedPreferences.Editor edit = sharedPreferences.edit();
                                edit.putInt(Constants.COMBO_BATCH_NUMBER, ++anInt);
                                edit.commit();
                            }

                            ToastUtil.showToast(ComboModifyAndAddActivity.this, "提交成功!");

                            allHandler.sendEmptyMessage(HandlerConstant.COMBO_SET_REFRESH);

                            finish();
                        } else {
                            ToastUtil.showToast(ComboModifyAndAddActivity.this, "提交失败!");
                        }
                    }

                    @Override
                    public void onFailure(Call<PutComboResultBean> call, Throwable t) {
                        hideLoadingView();
                        ToastUtil.showToast(ComboModifyAndAddActivity.this, "提交失败!");
                    }
                });
    }

    /**
     * 获取套餐中的物品
     *
     * @param comboId 套餐ID
     */

    private void getComboInfoData(int comboId) {
        showLoadingView(flEmpty);
        GetRetrofit.getInstance().getComboInfoData(NetAddress.token, NetAddress.machineCode, String.valueOf(comboId))
                .enqueue(new Callback<ComboInfoBean>() {
                    @Override
                    public void onResponse(Call<ComboInfoBean> call, Response<ComboInfoBean> response) {
                        ComboInfoBean body = response.body();
                        if (body != null && body.getData() != null && body.getData().size() != 0) {
                            comboInfolist.addAll(body.getData());
                            for (int i = 0; i < body.getData().size(); i++) {
                                ComboInfoBean.DataBean dataBean = body.getData().get(i);
                                idList.add(String.valueOf(dataBean.getGID()));
                            }
                        }
                        getData();
                    }

                    @Override
                    public void onFailure(Call<ComboInfoBean> call, Throwable t) {
                        getData();
                    }
                });

    }

    /**
     * 获取柜子中的物品
     */

    private void getData() {
        tvNumber.setText(String.valueOf(idList.size()));
        showLoadingView(flEmpty);
        GetRetrofit.getInstance().getCaidinalNumberAllGoods(NetAddress.token, NetAddress.machineCode, NetAddress.deptCode)
                .enqueue(new Callback<WarningInfoBean>() {
                    @Override
                    public void onResponse(Call<WarningInfoBean> call, Response<WarningInfoBean> response) {
                        WarningInfoBean body = response.body();
                        if (body != null && body.getData() != null && body.getData().size() != 0) {
                            List<WarningInfoBean.DataBean> data = body.getData();
                            list.addAll(data);
                            CardinalNumberSortUtils.sortCardinalNumberGoods(list, true);
                            for (int i = 0; i < comboInfolist.size(); i++) {
                                ComboInfoBean.DataBean bean = comboInfolist.get(i);
                                for (int j = 0; j < data.size(); j++) {
                                    WarningInfoBean.DataBean dataBean = data.get(j);
                                    if (bean.getGID() == dataBean.getGID()) {
                                        // 套餐中的物品 设置为选中,置顶
                                        list.remove(dataBean);
                                        dataBean.setComboMember(true);
                                        list.add(0, dataBean);
                                        break;
                                    }

                                }
                            }
                            sortList.clear();
                            sortList.addAll(list);
                            adapter.notifyDataSetChanged();
                        } else {
                            showEmptyView(flEmpty);
                        }
                        hideLoadingView();
                    }

                    @Override
                    public void onFailure(Call<WarningInfoBean> call, Throwable t) {
                        hideLoadingView();
                        showEmptyView(flEmpty);
                    }
                });
    }

    @Override
    public void onCheckListener(boolean isChecked, int id) {
        if (isChecked) {
            idList.add(String.valueOf(id));
        } else {
            idList.remove(String.valueOf(id));
        }
        tvNumber.setText(String.valueOf(idList.size()));
    }

    private void sort(int type) {
        if (type == 1) { // 按物品名排序
            if (sortGoods != 2) {
                isSortGoods = !isSortGoods;
                sortGoods++;
                CardinalNumberSortUtils.sortCardinalNumberGoods(list, isSortGoods);
            } else {
                clearSortDate();
            }
        } else {
            sortGoods = 0;
            isSortGoods = false;
        }

        if (type == 2) { // 按供应商排序
            if (sortSupplier != 2) {
                sortSupplier++;
                isSortSupplier = !isSortSupplier;
                CardinalNumberSortUtils.sortCardinalNumberSupplier(list, isSortSupplier);
            } else {
                clearSortDate();
            }
        } else {
            sortSupplier = 0;
            isSortSupplier = false;
        }

        if (type == 3) {
            if (sortSpecification != 2) {
                sortSpecification++;
                isSortSpecification = !isSortSpecification;
                CardinalNumberSortUtils.sortCardinalNumberSpecification(list, isSortSpecification);
            } else {
                clearSortDate();
            }
        } else {
            sortSpecification = 0;
            isSortSpecification = false;
        }

        ViewUtil.setSortColor(this, tvGoods, ivGoodsSort, sortGoods);
        ViewUtil.setSortColor(this, tvSupplier, ivSupplierSort, sortSupplier);
        ViewUtil.setSortColor(this, tvSize, ivSpecificationSort, sortSpecification);

        adapter.notifyDataSetChanged();
    }

    private void clearSortDate() {
        list.clear();
        list.addAll(sortList);
        sortGoods = 0;
        sortSupplier = 0;
        sortSpecification = 0;
    }
}
